package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.ConclusionVo;
import com.tanhua.domain.vo.OptionsVo;
import com.tanhua.domain.vo.QuestionnaireVo;
import com.tanhua.domain.vo.QuestionsVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoulApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class SoulService {

    @Reference
    private SoulApi soulApi;
    @Reference
    private UserInfoApi userInfoApi;

    public ResponseEntity<Object> testSoul() {
        //查找所有级别
        List<Questionnaire> questionnaires = soulApi.testSoul();
        //设置封装集合
        List<QuestionnaireVo> voList = new ArrayList<>();
        //判断集合是否为空
        if (!CollectionUtils.isEmpty(questionnaires)) {
            //遍历
            for (Questionnaire questionnaire : questionnaires) {
                //封装问卷id。等级..等等
                QuestionnaireVo qvo = new QuestionnaireVo();
                BeanUtils.copyProperties(questionnaire, qvo);
                //问卷id
                qvo.setId(questionnaire.getNid().toString());
                //根据用户id查询状态
                Map<String, Object> map = getIsLockAndReportId(UserHolder.getUserId(), questionnaire.getLevel());
                Integer isLock = (Integer) map.get("isLock");
                String reportId = (String) map.get("reportId");
                qvo.setReportId(reportId);
                qvo.setIsLock(isLock);

                //封装题目
                //根据等级id查找所有题目
                List<Topic> topics = soulApi.findAllTopic(questionnaire.getQid());
                List<QuestionsVo> questionsVo = new ArrayList<>();
                //判断集合是否为空并遍历
                if (!CollectionUtils.isEmpty(topics)) {
                    for (Topic topic : topics) {
                        //封装所有题目和id
                        QuestionsVo qtVo = new QuestionsVo();
                        qtVo.setId(topic.getTopId().toString());
                        qtVo.setQuestion(topic.getQuestion());
                        //封装选项
                        //根据题目id查找所有选项
                        List<Options> optionsList = soulApi.findAllOptions(topic.getTopId());
                        //选项vo
                        List<OptionsVo> opVo = new ArrayList<>();
                        //判断集合是否为空并遍历
                        if (!CollectionUtils.isEmpty(optionsList)) {
                            for (Options options : optionsList) {
                                //封装所有选项和id
                                OptionsVo optionsVo = new OptionsVo();
                                optionsVo.setId(options.getKeyId());
                                optionsVo.setOption(options.getOptions());
                                //添加到选项vo
                                opVo.add(optionsVo);
                            }
                        }
                        qtVo.setOptions(opVo);
                        //添加到题目vo
                        questionsVo.add(qtVo);
                    }
                }
                qvo.setQuestions(questionsVo);
                //添加返回的vo集合
                voList.add(qvo);
            }
        }
        return ResponseEntity.ok(voList);
    }
    //根据用户id查询状态
    private Map<String, Object> getIsLockAndReportId(Long userId,String level) {
        Boolean flag=true;
        Integer reportId = null;
        String reportIdStr = null;
        Integer isLocks=null;
        //根据用户id查询报告表
        List<Conclusion> conclusions= soulApi.findConclusion(userId);
        if(!CollectionUtils.isEmpty(conclusions)){
            for (Conclusion conclusion : conclusions) {
                if(conclusion.getLevel().equals(level)){
                    reportId=conclusion.getType();
                    flag=conclusion.getIsLock();
                    if(level.equals("初级")){
                        flag=false;
                    }
                }
            }
        }else if(level.equals("初级")){
            flag=false;
        }
        if(flag){
            isLocks=1;
        }else {
            isLocks=0;
        }
        if (reportId != null) {
            reportIdStr = reportId.toString();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("isLock", isLocks);
        map.put("reportId", reportIdStr);
        return map;
    }

    public ResponseEntity<Object> submitSoul(List<Object> answers) {
        Double score=0.0;
        Integer questionId = null;
        for (int i = 0; i < 10; i++) {
             Map<String, String> map = (Map<String, String>) answers.get(i);
             questionId = Integer.valueOf(map.get("questionId"));
             String optionId = map.get("optionId");
             System.out.println("题目：" + questionId + "答案" + optionId);
            //计算分数
             score = score + soulApi.findScore(questionId, optionId);
        }
        //根据分数判断人格类型
        String type;
        if (score < 21) {
            type = "1";
        } else if (score <= 40) {
            type = "2";
        } else if (score <= 55) {
            type = "3";
        } else {
            type = "4";
        }
        //根据题目id获取等级
        Integer qid = soulApi.findQid(questionId);
        String level = soulApi.findLevel(qid);

        Conclusion conclusion = new Conclusion();
        conclusion.setUserId(UserHolder.getUserId());
        conclusion.setLevel(level);
        conclusion.setType(Integer.valueOf(type));
        conclusion.setIsLock(false);
        conclusion.setReportId(type);
        conclusion.setScore(score);
        //保存报告
        soulApi.save(conclusion);
        Conclusion conclusions = new Conclusion();
        conclusions.setUserId(conclusion.getUserId());
        switch (level){
            case "初级":
                conclusions.setLevel("中级");
                conclusions.setIsLock(false);
                break;
            case "中级":
                conclusions.setLevel("高级");
                conclusions.setIsLock(false);
                break;
            default:
                break;
        }
        //如果报告存在就修改
        soulApi.update(conclusions);

        return ResponseEntity.ok(type);
    }

    public ResponseEntity<Object> report(Long reportId) {
        Long userId = UserHolder.getUserId();
        //根据报告id查询人物类型
        PersonalityType personalityType = soulApi.findReport(reportId);
        //2.创建要返回的报告Vo的对象
        ConclusionVo vo = new ConclusionVo();
        //3.设置报告Vo的里的报告内容和报告封面
        vo.setConclusion(personalityType.getConclusion());
        vo.setCover(personalityType.getCover());
        //4. 创建一个List<Map<String,String>>来存放纬度信息
        List<Map<String, String>> dimensionsList = new ArrayList<>();
        String ds = personalityType.getDimensions();
        String[] split = ds.split(",");
        for (String s : split) {
            Map<String, String> dimensions = new HashMap<>();
            String[] s2 = s.split("=");
            dimensions.put("key", s2[0]);
            dimensions.put("value", s2[1]);
            dimensionsList.add(dimensions);
        }
        vo.setDimensions(dimensionsList);
        //4. 创建一个List<Map<String,String>>来存相似的人
        List<Map<String, Object>> setSimilarYouList = new ArrayList<>();
        Set<Long> uidList = soulApi.findAllType(userId,reportId);
        if (!CollectionUtils.isEmpty(uidList)){
            for (Long uid : uidList) {
                if(uid!=userId) {
                    Map<String, Object> map = new HashMap<>();
                    UserInfo userInfo1 = userInfoApi.findById(uid);
                    map.put("id", uid.intValue());
                    map.put("avatar", userInfo1.getAvatar());
                    setSimilarYouList.add(map);
                }
            }
        }
       /* List<Map<String, String>> setSimilarYouList = new ArrayList<>();
        //根据用户id和报告id查询所有报告
        List<Conclusion> conclusionList = soulApi.findAllType(userId,reportId);
        if(!CollectionUtils.isEmpty(conclusionList)){
            for (Conclusion conclusion : conclusionList) {
                    UserInfo userInfo = userInfoApi.findById(conclusion.getUserId());
                    Map<String, String> map = new HashMap<>();
                    map.put("id",conclusion.getUserId().toString());
                    map.put("avatar",userInfo.getAvatar());
                    setSimilarYouList.add(map);
            }
        }*/
        vo.setSimilarYou(setSimilarYouList);

        return ResponseEntity.ok(vo);
    }
}
